﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SYSoft.Comm;
using SYSoft.Comm.Utils;
using SYSoft.Model;
using SYSoft.Model.Models.DeviceManage.DeviceData;
using SYSoft.Model.Models.DeviceManage.StockCheck;
using SYSoft.Model.ViewModels.DeviceData;
using SYSoft.Model.ViewModels.DeviceManage.YouqiPage;
using SYSoft.Model.ViewModels.Maintain;
using SYSoft.Model.ViewModels.StockCheck;
using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq;
using System.Threading.Tasks;

namespace SYSoft.Controllers.DeviceManage
{
    public class DeviceDataController : BaseController
    {
        public DeviceDataController()
        {

        }



        [HttpGet]
        public MessageModel GetRedisData(string key, string filed, string type)
        {
            HslCommunication.OperateResult<string> res = new HslCommunication.OperateResult<string>();
            if (type == "hash")
            {
                res = NetFactory.redisPool.ReadHashKey(key, filed);
            }
            else if (type == "string")
            {
                res = NetFactory.redisPool.ReadKey(key);
            }
            if (res.IsSuccess)
                return MessageModel.CreateSuccessResult(res.Content);
            else
                return new MessageModel(res.Message);
        }


        /// <summary>
        /// 导出 Excel
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Pu3000ChanlaingDataExcel(string startTime, string endTime)
        {
            MysqlHelper mysql = new MysqlHelper();
            string sql = $"select * from pu3000_chanliang where StartTime>='{startTime}' and StartTime<='{endTime}'";
            DataTable dataTable = mysql.ExecuteQuery(sql); // 此处准备 dataTable 数据
            if (dataTable == null || dataTable.Rows.Count < 1)
                return NotFound("未查询到数据！！");
            string name = "数据详情";
            byte[] bytes = ExcelHelper.DataTableToExcel(dataTable);
            return File(bytes, "application/octet-stream", $"{name}_{DateTime.Now:yyyyMMddHHmmssfff}.xls");
        }
        /// <summary>
        /// 查询pu3000产量 员工等数据
        /// </summary>
        /// <param name="deviceid"></param>
        /// <returns></returns>
        [HttpGet]
        public MessageModel<PageModel<PU3000ChanLiang>> Pu3000ChanlaingData(int page, int size, string startTime, string endTime)
        {
            MysqlHelper mysql = new MysqlHelper();
            PageModel<PU3000ChanLiang> models = new PageModel<PU3000ChanLiang>();
            DataTable dt = null;
            int dataCount = 0;
            dt = mysql.ExecuteQueryPage("pu3000_chanliang", $"StartTime>='{startTime}' and StartTime<='{endTime}'", "", "*", page, size, ref dataCount);
            models.dataCount = dataCount;
            models.page = page;
            models.PageSize = size;
            models.pageCount = dataCount % models.PageSize == 0 ? dataCount / models.PageSize : dataCount / models.PageSize + 1;
            models.data = new List<PU3000ChanLiang>();
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    models.data.Add(new PU3000ChanLiang
                    {
                        PeopleName = dt.Rows[i]["PeopleName"].ToString(),
                        IdCard = dt.Rows[i]["IdCard"].ToString(),
                        Bom = dt.Rows[i]["Bom"].ToString(),
                        Spece = dt.Rows[i]["Spece"].ToString(),
                        SerialNo = dt.Rows[i]["SerialNo"].ToString(),
                        Peibi = Convert.ToSingle(dt.Rows[i]["Peibi"]),
                        
                        ChanLiang = Convert.ToInt32(dt.Rows[i]["ChanLiang"]),
                        HandUsed= Convert.ToSingle(dt.Rows[i]["Guhua_hand"]) + Convert.ToSingle(dt.Rows[i]["Youqi_hand"]),
                        AutoUsed = Convert.ToSingle(dt.Rows[i]["Guhua_auto"]) + Convert.ToSingle(dt.Rows[i]["Youqi_auto"]),
                        //Guhua_hand = Convert.ToSingle(dt.Rows[i]["Guhua_hand"]),
                        //Youqi_hand = Convert.ToSingle(dt.Rows[i]["Youqi_hand"]),
                        //Guhua_auto = Convert.ToSingle(dt.Rows[i]["Guhua_auto"]),
                        //Youqi_auto = Convert.ToSingle(dt.Rows[i]["Youqi_auto"]),
                        StartTime = Convert.ToDateTime(dt.Rows[i]["StartTime"]),
                        EndTime = Convert.ToDateTime(dt.Rows[i]["EndTime"]),
                    });
                }
                return MessageModel.CreateSuccessResult(models);
            }
            else
            {
                return MessageModel.CreateFailedResult<PageModel<PU3000ChanLiang>>("");
            }
        }


        /// <summary>
        /// 导出 Excel
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult HunHeQiDataExcel(string startTime, string endTime)
        {
            MysqlHelper mysql = new MysqlHelper();
            string sql = $"select ARPress,CO2Press,PeibiPercent,ActruellyUsed,Outpress,CreatTime from data_hunheqi where CreatTime>='{startTime}' and CreatTime<='{endTime}'";
            DataTable dataTable = mysql.ExecuteQuery(sql); // 此处准备 dataTable 数据
            if (dataTable == null || dataTable.Rows.Count < 1)
                return NotFound("未查询到数据！！");
            string name = "数据详情";
            byte[] bytes = ExcelHelper.DataTableToExcel(dataTable);
            return File(bytes, "application/octet-stream", $"{name}_{DateTime.Now:yyyyMMddHHmmssfff}.xls");
        }
        /// <summary>
        /// 查询pu3000产量 员工等数据
        /// </summary>
        /// <param name="deviceid"></param>
        /// <returns></returns>
        [HttpGet]
        public MessageModel<PageModel<HunheQiModel>> HunHeQiData(int page, int size, string startTime, string endTime)
        {
            MysqlHelper mysql = new MysqlHelper();
            PageModel<HunheQiModel> models = new PageModel<HunheQiModel>();
            DataTable dt = null;
            int dataCount = 0;
            dt = mysql.ExecuteQueryPage("data_hunheqi", $"CreatTime>='{startTime}' and CreatTime<='{endTime}'", "", "*", page, size, ref dataCount);
            models.dataCount = dataCount;
            models.page = page;
            models.PageSize = size;
            models.pageCount = dataCount % models.PageSize == 0 ? dataCount / models.PageSize : dataCount / models.PageSize + 1;
            models.data = new List<HunheQiModel>();
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    models.data.Add(new HunheQiModel
                    {
                        ARPress = Convert.ToSingle(dt.Rows[i]["ARPress"]),
                        CO2Press = Convert.ToSingle(dt.Rows[i]["CO2Press"]),
                        PeibiPercent = Convert.ToSingle(dt.Rows[i]["PeibiPercent"]),
                        ActruellyUsed = Convert.ToSingle(dt.Rows[i]["ActruellyUsed"]),
                        Outpress = Convert.ToSingle(dt.Rows[i]["Outpress"]),
                        CreatTime = Convert.ToDateTime(dt.Rows[i]["CreatTime"])

                    });
                }
                return MessageModel.CreateSuccessResult(models);
            }
            else
            {
                return MessageModel.CreateFailedResult<PageModel<HunheQiModel>>("");
            }
        }
        /// <summary>
        /// 前端 根据type 来显示或者隐藏列，后端不做处理
        /// </summary>
        /// <param name="type"></param>
        /// <param name="devicename"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="page"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        [HttpGet]
        public MessageModel<PageModel<Check_Task>> GetStockCheckData(int type, string devicename, string startTime, string endTime, int page = 1, int size = 20)
        {
            MysqlHelper mysql = new MysqlHelper();
            PageModel<Check_Task> models = new PageModel<Check_Task>();
            DataTable dt = null;
            int dataCount = 0;
            if (type == 1) //总
            {
                dt = mysql.ExecuteQueryPage("dj_tasks", $"TaskStatus=0 and DeviceName='{devicename}' and StartCheckTime>='{startTime}' and StartCheckTime<='{endTime}'", "", "*", page, size, ref dataCount);
            }
            else if (type == 2)
            {
                dt = mysql.ExecuteQueryPage("dj_tasks", $"TaskStatus=1 and DeviceName='{devicename}' and StartCheckTime>='{startTime}' and StartCheckTime<='{endTime}'", "", "*", page, size, ref dataCount);
            }
            else if (type == 3) //异常已处理 
            {
                dt = mysql.ExecuteQueryPage("dj_tasks", $"TaskResult=1 and ErrorStatus=1 and DeviceName='{devicename}' and StartCheckTime>='{startTime}' and StartCheckTime<='{endTime}'", "", "*", page, size, ref dataCount);

                
            }
            else if (type == 4) //异常未处理
            {
                dt = mysql.ExecuteQueryPage("dj_tasks", $"DeviceName='{devicename}' and StartCheckTime>='{startTime}' and StartCheckTime<='{endTime}' and TaskResult=1 and ErrorStatus=0", "", "*", page, size, ref dataCount);
            }

            models.dataCount = dataCount;
            models.page = page;
            models.PageSize = size;
            models.pageCount = dataCount % models.PageSize == 0 ? dataCount / models.PageSize : dataCount / models.PageSize + 1;
            models.data = new List<Check_Task>();
            // DataTable dt = mysql.ExecuteQuery(sql);
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    models.data.Add(new Check_Task
                    {
                        DeviceName =  dt.Rows[i]["DeviceName"].ToString(),
                        DevicePosition =  dt.Rows[i]["DevicePosition"].ToString(),
                        TaskName =dt.Rows[i]["TaskName"].ToString(),
                        TaskContent = dt.Rows[i]["TaskContent"] == DBNull.Value ? "" : dt.Rows[i]["TaskContent"].ToString(),        
                        OperatorPeople = dt.Rows[i]["OperatorPeople"] == DBNull.Value ? "" : dt.Rows[i]["OperatorPeople"].ToString(),
                        TaskBeizhu = dt.Rows[i]["TaskBeizhu"]==DBNull.Value?"":dt.Rows[i]["TaskBeizhu"].ToString(),
                        TaskResult =Convert.ToInt32(  dt.Rows[i]["TaskResult"]),
                        TaskStatus = Convert.ToInt32(dt.Rows[i]["TaskStatus"]),
                        StartCheckTime =Convert.ToDateTime( dt.Rows[i]["StartCheckTime"]),
                        ErrorFinishResult = dt.Rows[i]["ErrorFinishResult"] == DBNull.Value ? "" : dt.Rows[i]["ErrorFinishResult"].ToString(),
                       
                    });


                }
                return MessageModel.CreateSuccessResult(models);
            }
            else
            {
                return MessageModel.CreateFailedResult<PageModel<Check_Task>>("");
            }

        }





        /// <summary>
        /// 前端 根据type 来显示或者隐藏列，后端不做处理
        /// </summary>
        /// <param name="type"></param>
        /// <param name="deviceid"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="page"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        [HttpGet]
        public MessageModel<PageModel<ElectricMeter>> GetEnergyData(int type ,int deviceid, string startTime, string endTime, int page = 1, int size = 20)
        {
            MysqlHelper mysql = new MysqlHelper();
            PageModel<ElectricMeter> models = new PageModel<ElectricMeter>();
            DataTable dt = null;
            int dataCount = 0;

            if (type == 1) //总
            {
                dt = mysql.ExecuteQueryPage("stat_alldeviceenergy", $"DeviceId={deviceid} and CreatTime>='{startTime}' and CreatTime<='{endTime}'", "", "*", page, size, ref dataCount);

            }
            else
            {
                if (deviceid == DeviceID.翻转机)
                {
                    dt = mysql.ExecuteQueryPage("data_energy", $"DeviceId={DeviceID.组焊} and SubDeviceId={4} and CreatTime>='{startTime}' and CreatTime<='{endTime}'", "", "*", page, size, ref dataCount);
                }
                else
                {
                    dt = mysql.ExecuteQueryPage("data_energy", $"DeviceId={deviceid} and CreatTime>='{startTime}' and CreatTime<='{endTime}'", "", "*", page, size, ref dataCount);
                }
                
            }

            models.dataCount = dataCount;
            models.page = page;
            models.PageSize = size;
            models.pageCount = dataCount % models.PageSize == 0 ? dataCount / models.PageSize : dataCount / models.PageSize + 1; 
            models.data = new List<ElectricMeter>();
          // DataTable dt = mysql.ExecuteQuery(sql);
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (type == 1)
                    {
                        models.data.Add(new ElectricMeter
                        {
                            DeviceId = Convert.ToInt32(dt.Rows[i]["DeviceId"]),
                            EPI_power = Convert.ToSingle(dt.Rows[i]["ActualEnergy"]),
                            CreatTime = dt.Rows[i]["CreatTime"].ToString(),
                        });
                    }
                    else
                    {
                        models.data.Add(new ElectricMeter
                        {
                            DeviceId = Convert.ToInt32(dt.Rows[i]["DeviceId"]),
                            CurrentA = Convert.ToSingle(dt.Rows[i]["CurrentA"]),
                            CurrentB = Convert.ToSingle(dt.Rows[i]["CurrentB"]),
                            CurrentC = Convert.ToSingle(dt.Rows[i]["CurrentC"]),
                            VoltageA = Convert.ToSingle(dt.Rows[i]["VoltageA"]),
                            VoltageB = Convert.ToSingle(dt.Rows[i]["VoltageB"]),
                            VoltageC = Convert.ToSingle(dt.Rows[i]["VoltageC"]),
                            S_power = Convert.ToSingle(dt.Rows[i]["S_power"]),
                            P_power = Convert.ToSingle(dt.Rows[i]["P_power"]),
                            Q_power = Convert.ToSingle(dt.Rows[i]["Q_power"]),
                            EPI_power = Convert.ToSingle(dt.Rows[i]["EPI_power"]),
                            CreatTime = dt.Rows[i]["CreatTime"].ToString(),
                        });
                    }
                   
                }
                return MessageModel.CreateSuccessResult(models);
            }
            else
            {
                return MessageModel.CreateFailedResult<PageModel<ElectricMeter>>("");
            }

        }




        /// <summary>
        /// 动态获取设备 数据  因为设备字段不统一
        /// </summary>
        /// <param name="deviceid"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<OtherPageModel<DynamicTableData>>> GetTableData(int deviceid, int page = 1, int size = 20, string startTime = "2021-11-12 15:00:00", string endTime = "2021-11-12 17:50:00")
        {
            OtherPageModel<DynamicTableData> pageModel = new OtherPageModel<DynamicTableData>();
            DateTime dt = DateTime.Now;
            DynamicTableData dynamicTable = new DynamicTableData();
            dynamicTable.tableColumns = new List<TableColumns>();
            dynamicTable.tableData = new List<TableData>();
            InfluxDbHelper influx = new InfluxDbHelper();
            List<int> indexarray = new List<int>();

            if (deviceid == DeviceID.PU3000)
            {

            }
            else  // PassData
            {
                //var model = ServerInfo.devicePasses[deviceid];
                //for (int i = 0; i < model.Count; i++)
                //{

                //    dynamicTable.tableColumns.Add(new TableColumns
                //    {
                //        label = model[i].PassName,
                //        prop = "Value" + (i + 1).ToString()
                //    });


                //}
                //dynamicTable.tableColumns.Add(new TableColumns
                //{
                //    label = "创建时间",
                //    prop = "time"
                //});
                // 分页查询
                string sqlstr = $"SELECT * FROM {"PassData" + deviceid.ToString()} WHERE time>='{startTime}' and time<='{endTime}'";
                var result = await influx.GetDataCount(sqlstr);
                if (result > 0)
                {
                    pageModel.dataCount = result;
                    pageModel.page = page;
                    pageModel.PageSize = size;
                    pageModel.pageCount = result / pageModel.PageSize;
                }

                //如果直接写  LIMIT rows OFFSET (page - 1)*rows 查询报错，可以  (page - 1)*rows 先计算出来，再放进去。OFFSET  表示从第几个开始显示
                int count = (page - 1) * size;

                string sql = $"SELECT * FROM {"PassData" + deviceid.ToString()} WHERE time>='{startTime}' and time<='{endTime}' LIMIT {size} OFFSET {count}";
                var table = await influx.GetData(sql);
                
                JArray obj = new JArray();

                if (table != null && table.Values.Count > 0)
                {
                    int titlecount = 0;
                    for (int j = 0; j < table.Columns.Count; j++)  // 多少列数据
                    {
                        if (table.Columns[j] != "time")
                        {
                            if (ServerInfo.devicePasses[deviceid].FirstOrDefault(x => x.PassName == table.Columns[j]) != null)
                            {
                                titlecount++;
                                dynamicTable.tableColumns.Add(new TableColumns
                                {
                                    label = table.Columns[j],
                                    prop = "Value" + titlecount.ToString()
                                });
                            }
                        }
                        else
                        {
                            dynamicTable.tableColumns.Add(new TableColumns
                            {
                                label = "创建时间",
                                prop = "time"
                            });
                        }

                    }

                    var list = table.Values;
                    for (int i = 0; i < list.Count; i++) // 多少行数据
                    {
                        TableData data = new TableData();
                        int valuecount = 0;
                        for (int j = 0; j < table.Columns.Count; j++)  // 多少列数据
                        {
                            if (table.Columns[j] != "time")
                            {
                                if(ServerInfo.devicePasses[deviceid].FirstOrDefault(x=>x.PassName== table.Columns[j])!=null)
                                {
                                    valuecount++;
                                    string t = list[i][j] == null ? "0" : list[i][j].ToString();
                                    data.SetValue(valuecount,float.Parse(t));
                                }                               
                            }
                            else
                            {
                                data.time = list[i][j].ToString();
                            }

                        }
                        dynamicTable.tableData.Add(data);
                    }
                    pageModel.data = dynamicTable;
                }
                else
                {
                    return MessageModel.CreateFailedResult<OtherPageModel<DynamicTableData>>("");
                }
            }

            return MessageModel.CreateSuccessResult(pageModel);

        }


        /// <summary>
        /// 导出 Excel
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async  Task<IActionResult> ExportExcel(dynamic obj)
        {
            //string tablename = obj["tablename"].ToString();
            //string deviceid = obj["deviceid"].ToString();
            //string starttime = obj["starttime"].ToString();
            //string endtime = obj["endtime"].ToString();

            dynamic objdyn = JsonConvert.DeserializeObject(Convert.ToString(obj));
            DataTable dataTable = null;
            string sql = "";
            if (objdyn.model.ToString() == "1")
            {
                string tablename = objdyn.tablename.ToString();
                string deviceid = objdyn.deviceid.ToString();
                string starttime = objdyn.starttime.ToString();
                string endtime = objdyn.endtime.ToString();
                if (Convert.ToInt32(deviceid) == DeviceID.翻转机)
                {
                    if(tablename== "data_energy")
                    {
                        sql = $"select * from {tablename} where DeviceId={DeviceID.组焊} and SubDeviceId={4}  and and CreatTime>='{starttime}' and  CreatTime<='{endtime}'";
                    }
                    else
                    {
                        sql = $"select * from {tablename} where DeviceId={deviceid} and CreatTime>='{starttime}' and  CreatTime<='{endtime}'";
                    }
                   
                }
                else{
                    sql = $"select * from {tablename} where DeviceId={deviceid} and CreatTime>='{starttime}' and  CreatTime<='{endtime}'";
                }
               
                MysqlHelper mysql = new MysqlHelper();
                dataTable = mysql.ExecuteQuery(sql); // 此处准备 dataTable 数据
            }
            else if (objdyn.model.ToString() == "3")
            {
                string sqlstr = objdyn.sqlstr.ToString();
                string starttime = objdyn.starttime.ToString();
                string endtime = objdyn.endtime.ToString();
                sql = $"{sqlstr} CreatTime>='{starttime}' and  CreatTime<='{endtime}'";
                MysqlHelper mysql = new MysqlHelper();
                dataTable = mysql.ExecuteQuery(sql); // 此处准备 dataTable 数据
            }

            else if (objdyn.model.ToString() == "2")
            {
                string tablename = objdyn.tablename.ToString();
                string starttime = Convert.ToDateTime( objdyn.starttime.ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                string endtime = Convert.ToDateTime(objdyn.endtime.ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                sql = $"select * from {tablename} where time>='{starttime}' and  time<='{endtime}'";

                InfluxDbHelper influx = new InfluxDbHelper();
                var table = await influx.GetData(sql);
                try
                {
                    if (table != null && table.Values.Count > 0)
                    {
                        dataTable = new DataTable();
                        for (int j = 0; j < table.Columns.Count; j++)  // 多少列数据
                        {
                            dataTable.Columns.Add(table.Columns[j].ToString());
                        }

                        var list = table.Values;
                        for (int i = 0; i < list.Count; i++) // 多少行数据
                        {
                            DataRow dr = dataTable.NewRow();
                            for (int j = 0; j < table.Columns.Count; j++)  // 多少列数据
                            {
                                dr[j] = list[i][j]==null?"": list[i][j];
                            }
                            dataTable.Rows.Add(dr);
                        }
                    }
                }
                catch (Exception ex)
                {
                    return NotFound(ex.Message);
                }                
            }
               
        
            if (dataTable == null || dataTable.Rows.Count < 1)
                return NotFound("未查询到数据！！");
            string name = "数据详情";
            byte[] bytes = ExcelHelper.DataTableToExcel(dataTable);
            return File(bytes, "application/octet-stream", $"{name}_{DateTime.Now:yyyyMMddHHmmssfff}.xls");
        }


        /// <summary>
        /// 导出点检 Excel
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ExportStockCheckExcel(dynamic obj)
        {
            dynamic objdyn = JsonConvert.DeserializeObject(Convert.ToString(obj));
            int type = Convert.ToInt32(objdyn.type1);
            string devicename = objdyn.devicename.ToString();
            string startTime = objdyn.starttime.ToString();
            string endTime = objdyn.endtime.ToString();
            MysqlHelper mysql = new MysqlHelper();
            string sql = "";
            DataTable dt = null;
            if (type == 1) //总
            {
                sql = $"select * from dj_tasks where TaskStatus=0 and DeviceName='{devicename}' and StartCheckTime>='{startTime}' and StartCheckTime<='{endTime}'";

            }
            else if (type == 2)
            {
                sql = $"select * from dj_tasks where TaskStatus=1 and DeviceName='{devicename}' and StartCheckTime>='{startTime}' and StartCheckTime<='{endTime}'";

            }
            else if (type == 3) // 异常未处理
            {
                sql = $"select * from dj_tasks where DeviceName='{devicename}' and StartCheckTime>='{startTime}' and StartCheckTime<='{endTime}' and TaskResult=1 and ErrorStatus=0";

            }
            else if (type == 4) //异常已处理
            {
                sql = $"select * from dj_tasks where TaskResult=1 and ErrorFinishResult=1 and DeviceName='{devicename}' and StartCheckTime>='{startTime}' and StartCheckTime<='{endTime}'";

            }
            dt = mysql.ExecuteQuery(sql); // 此处准备 dataTable 数据


            if (dt == null || dt.Rows.Count < 1)
                return NotFound("未查询到数据！！");
            string name = "数据详情";
            byte[] bytes = ExcelHelper.DataTableToExcel(dt);
            return File(bytes, "application/octet-stream", $"{name}_{DateTime.Now:yyyyMMddHHmmssfff}.xls");
        }


        /// <summary>
        /// 导出 CSV
        /// </summary>
        /// <returns></returns>
        [HttpGet("exportCSV")]
        public async Task<IActionResult> ExportCSV()
        {
            DataTable dataTable = new DataTable(); // 此处准备 dataTable 数据

            System.IO.Stream stream = ExcelHelper.DataTableToCsv(dataTable);
            return File(stream, "application/octet-stream", $"数据详情_{DateTime.Now:yyyyMMddHHmmssfff}.csv");
        }



        ///// <summary>
        /////     下载excel
        ///// </summary>
        ///// <returns></returns>
        //[HttpGet]
        //public async Task<ActionResult> DownLoadFileAsync([FromQuery] PriceToolsByWishParam priceToolsByShopeeParam)
        //{
        //    var data = await GetWishFreightAsync(priceToolsByShopeeParam);
        //    if (data == null)
        //        return BadRequest();
        //    var mapper = new Mapper();
        //    using var stream = new MemoryStream();
        //    mapper.Save(stream, data, "sheet1", true, true);
        //    return File(stream.ToArray(), "application/vnd.ms-excel",
        //        priceToolsByShopeeParam.Name + DateTime.Now.ToString("yyyy-MM-ddHH:mm:ss") + ".xlsx");
        //}


        /// <summary>
        /// 设备急停
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public MessageModel DeviceStop(int deviceid)
        {

            return MessageModel.CreateSuccessResult();
        }



        /// <summary>
        /// 获取实时能耗数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public MessageModel GetRealEnergyData(int deviceid)
        {
            var res = NetFactory.redisPool.ReadHashKey("MTCD:EnergyGateWay", deviceid.ToString());
            if (res.IsSuccess)
            {
                ElectricMeter electric = new ElectricMeter();
                JArray obj = JArray.Parse(res.Content);
                int online = 0;
                for (int i = 0; i < obj.Count; i++)
                {
                    JObject item1 = (JObject)obj[i];
                    if (item1.Value<bool>("IsActive"))
                    {
                        online++;
                        electric.CurrentA = item1.Value<float>("CurrentA");
                        electric.VoltageA = item1.Value<float>("VoltageA");
                        electric.EPI_power = electric.EPI_power + item1.Value<float>("EPI_power");
                    }
                }
                if (online > 0)
                    return MessageModel.CreateSuccessResult(electric);
                else
                    return new MessageModel("设备能耗不在线");
            }
            else
            {
                return new MessageModel(res.Message);
            }

        }


        /// <summary>
        /// 获取实时通道数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public MessageModel GetRealPassData(int deviceid)
        {
            var res = NetFactory.redisPool.ReadHashKey("MTCD:PassGateWay", deviceid.ToString());
            if (res.IsSuccess)
            {
                JObject obj = JObject.Parse(res.Content);
                if (obj.Value<bool>("IsActive"))
                {
                    List<YouqiPassDataVM> youqiPassDataVMs = new List<YouqiPassDataVM>();
                    int chanlaing=0;

                    if (obj.Property("DailyOutput") != null)
                    {
                        chanlaing = Convert.ToInt32(obj["DailyOutput"]); //产量
                    }
    
                   

                    JArray array = JArray.Parse(obj["PassData"].ToString());
                   
                    for (int i = 0; i < array.Count; i++)
                    {
                        var list = array[i].Children().ToList();
                        var p0 = list[0].ToObject<JProperty>();
                        var p1 = list[1].ToObject<JProperty>();
                        var p2 = list[2].ToObject<JProperty>();
                        var p3 = list[3].ToObject<JProperty>();
                        if (i % 2 == 0) // 偶数
                        {
                            youqiPassDataVMs.Add(new YouqiPassDataVM
                            {
                                ChanLiang =chanlaing,
                                PassName1 = p0.Name,
                                Value1 = p0.Value.ToString(),
                                lowLimitData1 = p1.Value.ToString(),
                                upLimitData1 = p2.Value.ToString(),
                                Unit1 = p3.Value.ToString(),
                            });
                        }
                        else  // 奇数 索引为 (i-1)/2
                        {
                            youqiPassDataVMs[(i - 1) / 2].PassName2 = p0.Name;
                            youqiPassDataVMs[(i - 1) / 2].Value2 = p0.Value.ToString();
                            youqiPassDataVMs[(i - 1) / 2].lowLimitData2 = p1.Value.ToString();
                            youqiPassDataVMs[(i - 1) / 2].upLimitData2 = p2.Value.ToString();
                            youqiPassDataVMs[(i - 1) / 2].Unit2 = p3.Value.ToString();
                        }
                    }

                    if (deviceid == DeviceID.油漆线)
                    {
                        var result = NetFactory.redisPool.ReadHashKey("MTCD:PassGateWay", DeviceID.油漆线脱附箱.ToString());
                        if (result.IsSuccess)
                        {
                            JObject objnew = JObject.Parse(result.Content);
                            if (objnew.Value<bool>("IsActive"))
                            {
                                List<YouqiPassDataVM> youqiPassDataVMsnew = new List<YouqiPassDataVM>();
                                JArray arraynew = JArray.Parse(objnew["PassData"].ToString());

                                for (int i = 0; i < arraynew.Count; i++)
                                {
                                    var list = arraynew[i].Children().ToList();
                                    var p0 = list[0].ToObject<JProperty>();
                                    var p1 = list[1].ToObject<JProperty>();
                                    var p2 = list[2].ToObject<JProperty>();
                                    var p3 = list[3].ToObject<JProperty>();
                                    if (i % 2 == 0) // 偶数
                                    {
                                        youqiPassDataVMsnew.Add(new YouqiPassDataVM
                                        {
                                            PassName1 = p0.Name,
                                            Value1 = p0.Value.ToString(),
                                            lowLimitData1 = p1.Value.ToString(),
                                            upLimitData1 = p2.Value.ToString(),
                                            Unit1 = p3.Value.ToString(),
                                        });
                                    }
                                    else  // 奇数 索引为 (i-1)/2
                                    {
                                        youqiPassDataVMsnew[(i - 1) / 2].PassName2 = p0.Name;
                                        youqiPassDataVMsnew[(i - 1) / 2].Value2 = p0.Value.ToString();
                                        youqiPassDataVMsnew[(i - 1) / 2].lowLimitData2 = p1.Value.ToString();
                                        youqiPassDataVMsnew[(i - 1) / 2].upLimitData2 = p2.Value.ToString();
                                        youqiPassDataVMsnew[(i - 1) / 2].Unit2 = p3.Value.ToString();
                                    }
                                }
                                for (int i = 0; i < youqiPassDataVMsnew.Count; i++)
                                {
                                    youqiPassDataVMs.Add(youqiPassDataVMsnew[i]);
                                }
                            }
                                
                        }
                    }
                    return MessageModel.CreateSuccessResult(youqiPassDataVMs);
                }
                else
                {
                    return new MessageModel("设备不在线");
                }
            }
            else
            {
                return new MessageModel(res.Message);
            }

        }


        /// <summary>
        /// 当月能耗消耗
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public MessageModel MonthEnergyUsed(int deviceid)
        {
            //从 1 号开始算
            DateTime dt1 = Convert.ToDateTime(DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-1" + " 00:00:00");
            DateTime dt2 = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59");
            List<float> data = new List<float>();
            MysqlHelper mysql = new MysqlHelper();
            string sql1 = $"select * from stat_alldeviceenergy where DeviceId={deviceid} and CreatTime>='{dt1.ToString("yyyy-MM-dd HH:mm:ss")}' and CreatTime<='{dt2.ToString("yyyy-MM-dd HH:mm:ss")}'";
            DataTable dt = mysql.ExecuteQuery(sql1);
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    data.Add(Convert.ToSingle(dt.Rows[i]["ActualEnergy"]));
                }
                return MessageModel.CreateSuccessResult(data);
            }
            else
            {
                return new MessageModel("未查询到数据");
            }
        }



        /// <summary>
        /// 当月产量
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public MessageModel MonthChanLiang(int deviceid)
        {
            //从 1 号开始算
            DateTime dt1 = Convert.ToDateTime(DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-1" + " 00:00:00");
            DateTime dt2 = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59");
            MysqlHelper mysql = new MysqlHelper();
            string sql1 = $"select * from stat_chanliang where DeviceId={deviceid} and CreatTime>='{dt1.ToString("yyyy-MM-dd HH:mm:ss")}' and CreatTime<'{dt2.ToString("yyyy-MM-dd HH:mm:ss")}'";
            DataTable dt = mysql.ExecuteQuery(sql1);
            int chanliang = 0;
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    chanliang += Convert.ToInt32(dt.Rows[i]["ChanLiang"]);
                }
                return MessageModel.CreateSuccessResult(chanliang);
            }
            else
            {
                return new MessageModel("未查询到数据");
            }
        }


        /// <summary>
        /// 获取点检图表统计数据（每个设备单独看板接口）
        /// </summary>
        /// <param name="devicename"></param>

        /// <returns></returns>
        [HttpGet]
        public MessageModel<StockCheckChartData> GetDeviceCheckChart(string devicename)
        {          
            MysqlHelper mysql = new MysqlHelper();
            StockCheckChartData data = new StockCheckChartData();
            string sql = $"select * from dj_tasks where  DeviceName='{devicename}' and StartCheckTime >= '{DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd HH:mm:ss")}' and StartCheckTime <= '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}'";
            var dt = mysql.ExecuteQuery(sql);
            if (dt != null && dt.Rows.Count > 0)
            {
                StockCheckCount value1 = new StockCheckCount();
                StockCheckCount value2 = new StockCheckCount();
                StockCheckCount value3 = new StockCheckCount();
                StockCheckCount value4 = new StockCheckCount();
                StockCheckCount value5 = new StockCheckCount();
                StockCheckCount value6 = new StockCheckCount();
                StockCheckCount value7 = new StockCheckCount();

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (Convert.ToDateTime(dt.Rows[i]["CreatTime"]).Day == DateTime.Now.Day)
                    {
                        data.stockCheckCount.CheckTotal++;
                        value1.CheckTotal++;

                        if (Convert.ToInt32(dt.Rows[i]["TaskStatus"]) == 1)
                        {
                            data.stockCheckCount.CheckedCount++;
                            value1.CheckedCount++;
                        }
                            
                        if (Convert.ToInt32(dt.Rows[i]["TaskResult"]) == 1)
                        {
                            data.stockCheckCount.WarnCount++;
                        }
                           
                        if (Convert.ToInt32(dt.Rows[i]["TaskResult"]) == 0 && Convert.ToInt32(dt.Rows[i]["TaskStatus"]) == 1)
                        {
                            data.stockCheckCount.OKCount++;
                            value1.OKCount++;
                        }
                           
                    }
                    if (Convert.ToDateTime(dt.Rows[i]["CreatTime"]).Day == DateTime.Now.AddDays(-1).Day)
                    {
                        value2.CheckTotal++;
                        if (Convert.ToInt32(dt.Rows[i]["TaskStatus"]) == 1)
                        {
                            value2.CheckedCount++;
                        }
                        if (Convert.ToInt32(dt.Rows[i]["TaskResult"]) == 0 && Convert.ToInt32(dt.Rows[i]["TaskStatus"]) == 1)
                        {
                            value2.OKCount++;
                        }
                    }
                    if (Convert.ToDateTime(dt.Rows[i]["CreatTime"]).Day == DateTime.Now.AddDays(-2).Day)
                    {
                        value3.CheckTotal++;
                        if (Convert.ToInt32(dt.Rows[i]["TaskStatus"]) == 1)
                        {
                            value3.CheckedCount++;
                        }
                        if (Convert.ToInt32(dt.Rows[i]["TaskResult"]) == 0 && Convert.ToInt32(dt.Rows[i]["TaskStatus"]) == 1)
                        {
                            value3.OKCount++;
                        }
                    }
                    if (Convert.ToDateTime(dt.Rows[i]["CreatTime"]).Day == DateTime.Now.AddDays(-3).Day)
                    {
                        value4.CheckTotal++;
                        if (Convert.ToInt32(dt.Rows[i]["TaskStatus"]) == 1)
                        {
                            value4.CheckedCount++;
                        }
                        if (Convert.ToInt32(dt.Rows[i]["TaskResult"]) == 0 && Convert.ToInt32(dt.Rows[i]["TaskStatus"]) == 1)
                        {
                            value4.OKCount++;
                        }
                    }
                    if (Convert.ToDateTime(dt.Rows[i]["CreatTime"]).Day == DateTime.Now.AddDays(-4).Day)
                    {
                        value5.CheckTotal++;
                        if (Convert.ToInt32(dt.Rows[i]["TaskStatus"]) == 1)
                        {
                            value5.CheckedCount++;
                        }
                        if (Convert.ToInt32(dt.Rows[i]["TaskResult"]) == 0 && Convert.ToInt32(dt.Rows[i]["TaskStatus"]) == 1)
                        {
                            value5.OKCount++;
                        }
                    }
                    if (Convert.ToDateTime(dt.Rows[i]["CreatTime"]).Day == DateTime.Now.AddDays(-5).Day)
                    {
                        value6.CheckTotal++;
                        if (Convert.ToInt32(dt.Rows[i]["TaskStatus"]) == 1)
                        {
                            value6.CheckedCount++;
                        }
                        if (Convert.ToInt32(dt.Rows[i]["TaskResult"]) == 0 && Convert.ToInt32(dt.Rows[i]["TaskStatus"]) == 1)
                        {
                            value6.OKCount++;
                        }
                    }
                    if (Convert.ToDateTime(dt.Rows[i]["CreatTime"]).Day == DateTime.Now.AddDays(-6).Day)
                    {
                        value7.CheckTotal++;
                        if (Convert.ToInt32(dt.Rows[i]["TaskStatus"]) == 1)
                        {
                            value7.CheckedCount++;
                        }
                        if (Convert.ToInt32(dt.Rows[i]["TaskResult"]) == 0 && Convert.ToInt32(dt.Rows[i]["TaskStatus"]) == 1)
                        {
                            value7.OKCount++;
                        }
                    }
                    //if (Convert.ToDateTime(dt.Rows[i]["CreatTime"]).Day == DateTime.Now.AddDays(-7).Day)
                    //{

                    //}
                }
                data.stockCheckCount.NoCheckedCount = data.stockCheckCount.CheckTotal- data.stockCheckCount.CheckedCount;

                //if (value1.CheckTotal > 1)
                //{
                //    data.checkHomeChart.Time.Add(DateTime.Now.ToString("MM.dd"));
                //    float ok = Convert.ToSingle(value1.OKCount) / Convert.ToSingle(value1.CheckTotal) * 100.0f;
                //    data.checkHomeChart.OKData.Add(ok);

                //    float finish = Convert.ToSingle(value1.CheckedCount) / Convert.ToSingle(value1.CheckTotal) * 100.0f;
                //    data.checkHomeChart.FinishData.Add(finish);
                //}

                if (value2.CheckTotal > 1)
                {
                    data.checkHomeChart.Time.Add(DateTime.Now.AddDays(-1).ToString("MM.dd"));
                    float ok = Convert.ToSingle(value2.OKCount) / Convert.ToSingle(value2.CheckTotal) * 100.0f;
                    data.checkHomeChart.OKData.Add(ok);

                    float finish = Convert.ToSingle(value2.CheckedCount) / Convert.ToSingle(value2.CheckTotal) * 100.0f;
                    data.checkHomeChart.FinishData.Add(finish);
                }
                if (value3.CheckTotal > 1)
                {
                    data.checkHomeChart.Time.Add(DateTime.Now.AddDays(-2).ToString("MM.dd"));
                    float ok = Convert.ToSingle(value3.OKCount) / Convert.ToSingle(value3.CheckTotal) * 100.0f;
                    data.checkHomeChart.OKData.Add(ok);

                    float finish = Convert.ToSingle(value3.CheckedCount) / Convert.ToSingle(value3.CheckTotal) * 100.0f;
                    data.checkHomeChart.FinishData.Add(finish);
                }
                if (value4.CheckTotal > 1)
                {
                    data.checkHomeChart.Time.Add(DateTime.Now.AddDays(-3).ToString("MM.dd"));
                    float ok = Convert.ToSingle(value4.OKCount) / Convert.ToSingle(value4.CheckTotal) * 100.0f;
                    data.checkHomeChart.OKData.Add(ok);

                    float finish = Convert.ToSingle(value4.CheckedCount) / Convert.ToSingle(value4.CheckTotal) * 100.0f;
                    data.checkHomeChart.FinishData.Add(finish);
                }
                if (value5.CheckTotal > 1)
                {
                    data.checkHomeChart.Time.Add(DateTime.Now.AddDays(-4).ToString("MM.dd"));
                    float ok = Convert.ToSingle(value5.OKCount) / Convert.ToSingle(value5.CheckTotal) * 100.0f;
                    data.checkHomeChart.OKData.Add(ok);

                    float finish = Convert.ToSingle(value5.CheckedCount) / Convert.ToSingle(value5.CheckTotal) * 100.0f;
                    data.checkHomeChart.FinishData.Add(finish);
                }
                if (value6.CheckTotal > 1)
                {
                    data.checkHomeChart.Time.Add(DateTime.Now.AddDays(-5).ToString("MM.dd"));
                    float ok = Convert.ToSingle(value6.OKCount) / Convert.ToSingle(value6.CheckTotal) * 100.0f;
                    data.checkHomeChart.OKData.Add(ok);

                    float finish = Convert.ToSingle(value6.CheckedCount) / Convert.ToSingle(value6.CheckTotal) * 100.0f;
                    data.checkHomeChart.FinishData.Add(finish);
                }
                if (value7.CheckTotal > 1)
                {
                    data.checkHomeChart.Time.Add(DateTime.Now.AddDays(-6).ToString("MM.dd"));
                    float ok = Convert.ToSingle(value7.OKCount) / Convert.ToSingle(value7.CheckTotal) * 100.0f;
                    data.checkHomeChart.OKData.Add(ok);

                    float finish = Convert.ToSingle(value7.CheckedCount) / Convert.ToSingle(value7.CheckTotal) * 100.0f;
                    data.checkHomeChart.FinishData.Add(finish);
                }

                data.checkHomeChart.Time.Reverse();
                data.checkHomeChart.OKData.Reverse();
                data.checkHomeChart.FinishData.Reverse();
                return MessageModel.CreateSuccessResult(data);

            }

            return  MessageModel.CreateFailedResult<StockCheckChartData>("数据没查询到");
        }





        /// <returns></returns>
        [HttpGet]
        public MessageModel<List<WHAlarmInfo>> GetWHTable(int deviceid,string devicename)
        {
            List<WHAlarmInfo> wHAlarmInfos = new List<WHAlarmInfo>();
            var res = NetFactory.redisPool.ReadHashKeyAll("MTCD:ErrorMaintain" + "-" + deviceid.ToString());
            if (res.IsSuccess)
            {    
                var data = res.Content;
                for (int i = 0; i < data.Length; i++)
                {
                    if (i % 2 == 0 )
                    {
                        wHAlarmInfos.Add(new WHAlarmInfo
                        {
                            WhType="预测性维护",
                            DeviceName = devicename,
                            PassName = data[i].Split('-')[1],
                            WHText = data[i + 1]
                        });
                    }
                }
            }
            MysqlHelper mysql = new MysqlHelper();
            string sql2 = $"select * from wh_tasks_data where Flag={1} and DeviceName='{devicename}'";
            DataTable dt = mysql.ExecuteQuery(sql2);
            if (dt != null && dt.Rows.Count > 0)
            {
                List<string> sqls = new List<string>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    wHAlarmInfos.Add(new WHAlarmInfo
                    {
                        WhType = "定期维护",
                        DeviceName = devicename,
                        PassName = dt.Rows[i]["TaskName"].ToString(),
                        WHText = dt.Rows[i]["TaskContent"].ToString(),
                    });
                }
            }

            if (wHAlarmInfos.Count > 0)
                return MessageModel.CreateSuccessResult(wHAlarmInfos);
            return new MessageModel<List<WHAlarmInfo>>();

        }


        /// 获取所有维护信息
        /// <returns></returns>
        [HttpGet]
        public MessageModel<List<WHAlarmInfo>> GetWHTableAll()
        {
            List<WHAlarmInfo> wHAlarmInfos = new List<WHAlarmInfo>();
           var cto = NetFactory.redisPool.ReadAllKeys("MTCD:ErrorMaintain" + "-*");
            if (cto.IsSuccess)
            {
                string[] keys = cto.Content;
                for (int j = 0; j < keys.Length; j++)
                {
                    var res = NetFactory.redisPool.ReadHashKeyAll(keys[j]);
                    if (res.IsSuccess)
                    {
                        var data = res.Content;
                        for (int i = 0; i < data.Length; i++)
                        {
                            if (i % 2 == 0)
                            {
                                wHAlarmInfos.Add(new WHAlarmInfo
                                {
                                    WhType = "预测性维护",
                                    DeviceName = ServerInfo.GetDevicename(Convert.ToInt32( keys[j].Split('-')[1])),
                                    PassName = data[i].Split('-')[1],
                                    WHText = data[i + 1],
                                    CreatTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                                });
                            }
                        }
                    }
                }
            }
           
            MysqlHelper mysql = new MysqlHelper();
            string sql2 = $"select * from wh_tasks_data where Flag={1}";
            DataTable dt = mysql.ExecuteQuery(sql2);
            if (dt != null && dt.Rows.Count > 0)
            {
                List<string> sqls = new List<string>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    wHAlarmInfos.Add(new WHAlarmInfo
                    {
                        WhType = "定期维护",
                        DeviceName = dt.Rows[i]["DeviceName"].ToString(),
                        PassName = dt.Rows[i]["TaskName"].ToString(),
                        WHText = dt.Rows[i]["TaskContent"].ToString(),
                        CreatTime = dt.Rows[i]["CreatTime"].ToString(),
                    });
                }
            }

            if (wHAlarmInfos.Count > 0)
                return MessageModel.CreateSuccessResult(wHAlarmInfos);
            return new MessageModel<List<WHAlarmInfo>>();

        }


    }
}
